package com.occludens.util;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class XMLUtil {

	/**
	 * Create a Document from a XML String
	 * @param context
	 * @param xmlValue -> String XML formatted
	 * @return a Document
	 * @throws Exception
	 */
	public static Document getXMLDocument(String xmlString) throws Exception {
		try {
			Document returnDocument = null;
			if (StringUtils.isNotBlank(xmlString)) {
				DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
				InputSource source = new InputSource();
				source.setCharacterStream(new StringReader(xmlString));

				returnDocument = builder.parse(source);
			}
			return returnDocument;
		} catch(Exception e) {
			throw e;
		}
	}

	/**
	 * Create a String from a Document
	 * @param context
	 * @param document
	 * @return a String XML formatted
	 * @throws Exception
	 */
	public static String getXMLString(Document xmlDocument) throws Exception {
		try {
			DOMSource source = new DOMSource(xmlDocument);
			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);
			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer();
			transformer.transform(source, result);
			writer.flush();
			return writer.toString();
		} catch(Exception e) {
			throw e;
		}
	}

}
